package com.example.service.impl;

import com.example.mapper.ArticleMapper;
import com.example.pojo.Article;
import com.example.pojo.PageBean;
import com.example.service.ArticleService;
import com.example.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ArticleServiceImpl implements ArticleService {

    private final ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize,
                                  final Integer categoryId, final String state) {
        // 创建PageBean对象用来封装查询好的对象
        PageBean<Article> pageBean = new PageBean<>();
        // 当前页和每页条数
        pageNum = pageNum == null || pageNum < 1 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        // 获取当前用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        final Integer userId = (Integer) map.get("id");

        // 当前页偏移量
        final Integer currentPage = (pageNum - 1) * pageSize;
        // 调用mapper
        List<Article> articles = articleMapper.list(currentPage, pageSize, userId, categoryId, state);

        pageBean.setItem(articles);
        pageBean.setTotal((long) articles.size());

        return pageBean;
    }

    @Override
    public Article findById(Integer id) {
        return articleMapper.findById(id);
    }

    @Override
    public void update(Article article) {
        articleMapper.update(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
